package com.djf.djfcs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.djf.djfcs.dto.OrderDetailResponse;
import com.djf.djfcs.dto.OrderQueryRequest;
import com.djf.djfcs.entity.Order;
import com.djf.djfcs.entity.UserDelivery;
import com.djf.djfcs.mapper.OrderMapper;
import com.djf.djfcs.mapper.UserDeliveryMapper;
import com.djf.djfcs.service.OrderQueryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单查询服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderQueryServiceImpl implements OrderQueryService {

    private final OrderMapper orderMapper;
    private final UserDeliveryMapper userDeliveryMapper;

    @Override
    public Page<OrderDetailResponse> queryOrderDetails(OrderQueryRequest request) {
        log.info("查询订单详情，用户ID: {}, 时间范围: {} - {}", 
                request.getUserId(), request.getStartTime(), request.getEndTime());

        // 1. 分页查询订单
        Page<Order> orderPage = new Page<>(request.getPageNum(), request.getPageSize());
        LambdaQueryWrapper<Order> orderWrapper = new LambdaQueryWrapper<Order>()
                .eq(Order::getUserId, request.getUserId())
                .between(Order::getCreateTime, request.getStartTime(), request.getEndTime())
                .eq(Order::getDeleted, 0)
                .orderByDesc(Order::getCreateTime);
        
        Page<Order> orderResult = orderMapper.selectPage(orderPage, orderWrapper);
        
        if (orderResult.getRecords().isEmpty()) {
            log.info("未找到符合条件的订单");
            return new Page<>(request.getPageNum(), request.getPageSize());
        }

        // 2. 获取订单ID列表
        List<Long> orderIds = orderResult.getRecords().stream()
                .map(Order::getId)
                .collect(Collectors.toList());

        // 3. 查询对应的配送信息
        LambdaQueryWrapper<UserDelivery> deliveryWrapper = new LambdaQueryWrapper<UserDelivery>()
                .in(UserDelivery::getOrderId, orderIds)
                .eq(UserDelivery::getDeleted, 0)
                .orderByDesc(UserDelivery::getCreateTime);
        
        List<UserDelivery> deliveries = userDeliveryMapper.selectList(deliveryWrapper);
        
        // 4. 按订单ID分组配送信息
        Map<Long, List<UserDelivery>> deliveryMap = deliveries.stream()
                .collect(Collectors.groupingBy(UserDelivery::getOrderId));

        // 5. 组装结果
        List<OrderDetailResponse> responseList = orderResult.getRecords().stream()
                .map(order -> {
                    List<UserDelivery> orderDeliveries = deliveryMap.getOrDefault(order.getId(), java.util.Collections.emptyList());
                    return new OrderDetailResponse(order, orderDeliveries);
                })
                .collect(Collectors.toList());

        // 6. 构建分页结果
        Page<OrderDetailResponse> result = new Page<>(request.getPageNum(), request.getPageSize());
        result.setRecords(responseList);
        result.setTotal(orderResult.getTotal());
        result.setPages(orderResult.getPages());
        
        log.info("查询完成，共找到 {} 条订单记录", responseList.size());
        return result;
    }
}